package apis

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"net/http"
	"strconv"
	"tuowei.com/app/admin/models"
	"tuowei.com/app/admin/service"
	"tuowei.com/app/admin/service/dto"
	"tuowei.com/common/actions"
	"tuowei.com/pkg/xlog"
)

type SysLecturer struct {
	api.Api
}

// GetPage
// @Summary 列表班主任信息数据
// @Description 获取JSON
// @Tags 班主任
// @Param username query string false "username"
// @Success 200 {string} {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-class [get]
// @Security Bearer
func (e SysLecturer) GetPage(c *gin.Context) {
	s := service.SysLecturer{}
	req := dto.SysLecturerGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	sd := &service.SysDept{}
	sd.Orm = e.Orm

	if req.DeptId != "" {
		DeptIdList := make([]int, 0)
		pid, _ := strconv.Atoi(req.DeptId)
		dtosd := &dto.SysDeptGetPageReq{}
		dtosd.ParentId = pid
		DeptIdList = append(DeptIdList, pid)
		var list []models.SysDept
		err = sd.GetList(dtosd, &list)
		if err != nil {
			xlog.Errorf("db error: %s", err)
			return
		}
		if len(list) == 0 {
			p := actions.GetPermissionFromContext(c)
			list := make([]models.SysLecturer, 0)
			var count int64
			err = s.GetPage(&req, p, &list, &count)
			if err != nil {
				e.Error(500, err, "查询失败")
				return
			}
			e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
			return
		} else {
			for _, l := range list {
				DeptIdList = append(DeptIdList, l.DeptId)
				dtosd1 := &dto.SysDeptGetPageReq{}
				dtosd1.ParentId = l.DeptId
				var list1 []models.SysDept
				err = sd.GetList(dtosd1, &list1)
				if err != nil {
					xlog.Errorf("db error: %s", err)
					return
				}
				for _, l := range list1 {
					DeptIdList = append(DeptIdList, l.DeptId)
				}

			}
		}
		db := e.Orm.Table("sys_lecturer")
		for i, l := range DeptIdList {
			if i == 0 {
				db.Where("dept_id=?", l)
			} else {
				db.Or("dept_id=?", l)
			}

		}
		listu := make([]models.SysLecturer, 0)
		var count int64
		err = db.Offset((req.GetPageIndex() - 1) * req.GetPageSize()).Limit(req.GetPageSize()).Count(&count).Find(&listu).Error
		if err != nil {
			xlog.Errorf("db error: %s", err)
			return
		}
		e.PageOK(listu, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
		return
	}
	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]models.SysLecturer, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

func (e SysLecturer) GetPageApp(c *gin.Context) {
	s := service.SysLecturer{}
	req := dto.SysLecturerGetPageReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.IsTop = 1

	//数据权限检查
	p := actions.GetPermissionFromContext(c)

	list := make([]models.SysLecturer, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Insert
// @Summary 创建班主任
// @Description 获取JSON
// @Tags 班主任
// @Accept  application/json
// @Product application/json
// @Param data body dto.SysCourseInsertReq true "班主任数据"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-course [post]
// @Security Bearer
func (e SysLecturer) Insert(c *gin.Context) {
	s := service.SysLecturer{}
	req := dto.SysLecturerInsertReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.Insert(&req)
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	e.OK(req.GetId(), "创建成功")
}

// Update
// @Summary 修改班主任数据
// @Description 获取JSON
// @Tags 班主任
// @Accept  application/json
// @Product application/json
// @Param data body dto.SysUserUpdateReq true "body"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-class/{lecturerId} [put]
// @Security Bearer
func (e SysLecturer) Update(c *gin.Context) {
	s := service.SysLecturer{}
	req := dto.SysLecturerUpdateReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.Update(&req)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "更新成功")
}

// Delete
// @Summary 删除班主任数据
// @Description 删除数据
// @Tags 班主任
// @Param userId path int true "lecturerId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-class/{lecturerId} [delete]
// @Security Bearer
func (e SysLecturer) Delete(c *gin.Context) {
	s := service.SysLecturer{}
	req := dto.SysLecturerById{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	//校验教师是否在使用
	for _, id := range req.Ids {
		cou := models.SysCourse{}
		e.Orm.Table(cou.TableName()).Where("deleted_at is null and lecturer_id=?", id).First(&cou)
		if cou.CourseId != 0 {
			xlog.Error("教师正在使用 lecturer_id:", req.Id)
			e.Error(500, err, "教师正在使用 不能删除")
			return
		}
		ocou := models.SysOfflineCourse{}
		e.Orm.Table(ocou.TableName()).Where("deleted_at is null and lecturer_id=?", id).First(&ocou)
		if ocou.CourseId != 0 {
			xlog.Error("教师正在使用 lecturer_id:", req.Id)
			e.Error(500, err, "教师正在使用 不能删除")
			return
		}
		//线下订单招生老师
		oo := models.OfflineOrder{}
		e.Orm.Table(oo.TableName()).Where("deleted_at is null and enrollment_teacher_id=?", id).First(&oo)
		if ocou.CourseId != 0 {
			xlog.Error("教师正在使用 lecturer_id:", req.Id)
			e.Error(500, err, "教师正在使用 不能删除")
			return
		}
	}

	// 设置删除人
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))

	// 数据权限检查
	p := actions.GetPermissionFromContext(c)

	err = s.Remove(&req, p)
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.OK(req.GetId(), "删除成功")
}

func (e SysLecturer) List(c *gin.Context) {
	s := service.SysLecturer{}
	req := dto.SysLecturerSearchReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	list := make([]models.SysLecturerList, 0)
	err = s.GetList(&req, &list)
	if err != nil {
		e.Error(500, err, "查询失败")
		return
	}

	e.OK(list, "查询成功")
}

// Delete
// @Summary 修改置顶状态数据
// @Description 删除数据
// @Tags
// @Param userId path int true "lecturerId"
// @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-class/{lecturerId} [delete]
// @Security Bearer
func (e SysLecturer) UpdateTopStatus(c *gin.Context) {
	s := service.SysLecturer{}
	req := dto.SysLecturerUpdateTopStatusReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	// 设置更新者
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))

	// 数据权限检查
	p := actions.GetPermissionFromContext(c)

	err = s.UpdateTopStatus(&req, p)
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.OK(nil, "成功")
}

func (e SysLecturer) Get(c *gin.Context) {
	s := service.SysLecturer{}
	req := dto.SysLecturerById{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var object models.SysLecturer
	//数据权限检查
	p := actions.GetPermissionFromContext(c)
	err = s.Get(&req, p, &object)
	if err != nil {
		e.Error(http.StatusUnprocessableEntity, err, err.Error())
		return
	}
	e.OK(object, "查询成功")
}

func (e SysLecturer) ChangeStatus(c *gin.Context) {
	s := service.SysLecturer{}
	req := dto.SysLecturerUpdateStatusReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req, binding.JSON, nil).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c), user.GetUserName(c))
	err = s.UpdateStatus(&req)
	if err != nil {
		e.Error(500, err, "更新失败")
		return
	}
	e.OK(req.GetId(), "更新成功")
}
